package com.xiaomaoguai.fcp.pre.kepler.router.rpc.httpconverter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import com.xiaomaoguai.fcp.pre.kepler.router.buf.Buf;

public class HessianHttpConverter extends AbstractHttpMessageConverter<Buf> {

	private final HessianSerializer hessianSerializer = new HessianSerializer();

	public HessianHttpConverter() {
		setSupportedMediaTypes(
				Collections.singletonList(new MediaType("application", "kepler-hessian", Charset.forName("UTF-8"))));
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		return Buf.class.isAssignableFrom(clazz);
	}

	@Override
	protected Buf readInternal(Class<? extends Buf> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		return clazz.cast(hessianSerializer.readObject(inputMessage.getBody()));
	}

	@Override
	protected void writeInternal(Buf buf, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		HttpHeaders headers = outputMessage.getHeaders();
		byte[] bytes = null;
		bytes = hessianSerializer.writeObject(buf);
		headers.setContentLength(bytes.length);
		outputMessage.getBody().write(bytes);
	}

}
